package com.yike.user.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.v3.ApiClient;
import com.alipay.v3.ApiException;
import com.alipay.v3.Configuration;
import com.alipay.v3.api.AlipayFundTransUniApi;
import com.alipay.v3.model.*;
import com.alipay.v3.util.model.AlipayConfig;
import com.yike.common.tool.StringUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @author Sakura
 * @date 2024/9/18 9:16
 * 阿里转账工具类
 */
@Component
@Log4j2
public class AlipayTransferUtil {

    @Value("${alipay.trans.server-url}")
    String serverUrl;

    @Value("${alipay.trans.app-id}")
    String appId;

    @Value("${alipay.trans.private-key}")
    String privateKey;

    @Value("${alipay.trans.app-cert-path}")
    String appCertPath;

    @Value("${alipay.trans.alipay-public-cert-path}")
    String alipayPublicCertPath;

    @Value("${alipay.trans.root-cert-path}")
    String rootCertPath;

    private AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl(serverUrl);
        alipayConfig.setAppId(appId);
        alipayConfig.setPrivateKey(privateKey);
        alipayConfig.setAppCertPath(appCertPath);
        alipayConfig.setAlipayPublicCertPath(alipayPublicCertPath);
        alipayConfig.setRootCertPath(rootCertPath);
        return alipayConfig;
    }

    public String transfer(String outBizNo, BigDecimal transAmount, String loginId, String userName, String orderTitle) throws ApiException {

        ApiClient defaultClient = Configuration.getDefaultApiClient();
        // 初始化alipay参数（全局设置一次）
        defaultClient.setAlipayConfig(getAlipayConfig());

        // 构造请求参数以调用接口
        AlipayFundTransUniApi api = new AlipayFundTransUniApi();
        AlipayFundTransUniTransferModel data = new AlipayFundTransUniTransferModel();

        // 设置商家侧唯一订单号
        data.setOutBizNo(outBizNo);

        // 设置订单总金额
        data.setTransAmount(transAmount.toString());

        // 设置描述特定的业务场景
        data.setBizScene("DIRECT_TRANSFER");

        // 设置业务产品码
        data.setProductCode("TRANS_ACCOUNT_NO_PWD");

        if (StringUtil.isNotBlank(orderTitle)) {
            // 设置转账业务的标题
            data.setOrderTitle(orderTitle);

            // 设置业务备注
            data.setRemark(orderTitle);
        }

        // 设置原支付宝业务单号
        //data.setOriginalOrderId("20190620110075000006640000063056");

        // 设置收款方信息
        Participant payeeInfo = new Participant();
        payeeInfo.setIdentity(loginId);
        payeeInfo.setName(userName);
        payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
        data.setPayeeInfo(payeeInfo);



        // 设置转账业务请求的扩展参数
        data.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");

        // 设置签名信息
//        SignData signData = new SignData();
//        signData.setOriSign("EqHFP0z4a9iaQ1ep==");
//        signData.setPartnerId("签名被授权方支付宝账号ID");
//        signData.setOriAppId("2021000185629012");
//        signData.setOriOutBizNo("商户订单号");
//        signData.setOriSignType("RSA2");
//        signData.setOriCharSet("UTF-8");
//        data.setSignData(signData);

        try {
            AlipayFundTransUniTransferResponseModel response = api.transfer(data);
            log.info("调用支付宝转账接口返回:" + JSON.toJSONString(response));

            return "ok";
        } catch (ApiException e) {
            String str = e.getResponseBody();  // 获取错误对象
            log.error("调用支付宝转账接口异常: " +str);

            JSONObject jsonObject = JSONObject.parseObject(str);
            return jsonObject.getString("message");
        }
    }


}
